package com.basic.technology.study.introduction.thread.juc.CyclicBarrier;

import com.basic.technology.study.introduction.thread.juc.semaphore.SemaphorePractice;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierPractice {

    public static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

    public static class T extends Thread {

        public T(String name) {
            super(name);
        }

        @Override
        public void run() {
            try {
                //模拟休眠
                TimeUnit.SECONDS.sleep(2);
                long starTime = System.currentTimeMillis();
                //调用await()的时候，当前线程将会被阻塞，需要等待其他员工都到达await了才能继续
                cyclicBarrier.await();
                long endTime = System.currentTimeMillis();
                System.out.println(this.getName() + " 等待了" + (endTime - starTime) + "(ms),开始吃饭了！");
            } catch (InterruptedException e) {
                System.out.println("-------interrupt----------" + Thread.currentThread().getName());
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                System.out.println("-------brokenBarrier----------" + Thread.currentThread().getName());
                e.printStackTrace();
            }
        }
    }

    /**
     * 当等待中的一个线程被打断(interrupt)，相当于这个barrier被破坏
     * */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            T t = new T("ttt:" + i);
            t.start();
            TimeUnit.SECONDS.sleep(5);
            if (i == 1) {
                t.interrupt();
            }
        }
    }

}
